package com.clp.util;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * Json字符串转换工具
 */
@Slf4j
public class JsonUtil {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }

    public static <T> T jsonToObject(String text, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(text, typeReference);
        } catch (IOException e) {
            log.error("json parse err,json:{}", text, e);
            throw new RuntimeException(e);
        }
    }

//    @SneakyThrows
//    public static String objectToJson(Object object) {
//        return objectMapper.writeValueAsString(object);
//    }

    /**
     * 将对象转换为字符串
     *
     * @param obj
     * @return
     */
    public static String objectToJson(Object obj) {
        if (obj == null) {
            throw new NullPointerException();
        }
        return JSON.toJSONString(obj);
    }

    /**
     * 将json对象还原为对象
     */
    public static <T> T jsonToObject(String jsonStr, Class<T> clazz) {
        if (jsonStr == null || jsonStr.equals("")) {
            return null;
        }
        try {
            return JSON.parseObject(jsonStr, clazz);
        } catch (Exception e) {
            System.out.println(1);
            throw e;
        }
    }

    public static <T> T jsonToObject(byte[] bytes, Class<T> clazz) {
        if (bytes == null || bytes.length == 0) {
            throw new NullPointerException();
        }
        return JSON.parseObject(bytes, clazz);
    }
}
